﻿package component.formula.function;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import component.formula.FormulaInfo;
import component.formula.constant.FormulaConstant;
import component.formula.constant.TreeConstant;
import component.formula.exception.FormulaException;
import component.formula.util.ITreeOrder;
import component.formula.util.TreeOrder;

public class TreeHead implements IReportFunction {

	public Object calculate(String expression, FormulaInfo formulaInfo,
			List dataList) throws FormulaException {
		List retList = new ArrayList();

		String[] paraArr = expression.split(",");
		String colName = paraArr[0].trim(); // 显示的字段名
		String compareName = paraArr[1].trim(); // 用于比较的字段名
		String parentIdName = paraArr[2].trim(); // 父ID值的字段名
		String rootId = paraArr[3].trim(); // 根节点的值
		String orderName = ""; // 排序的字段名
		if (paraArr.length > 3) {
			orderName = paraArr[4].trim();
		}

		ITreeOrder treeOrderUtil = new TreeOrder();
		treeOrderUtil.setIdName(compareName);
		treeOrderUtil.setOrderName(orderName);
		treeOrderUtil.setParentIdName(parentIdName);
		treeOrderUtil.setRootId(rootId);
		dataList = treeOrderUtil.orderTree2(dataList);
		
		Map idMap = new HashMap();//用于定位父节点的位置 
		retList = dataList;
		for (int i = 0; i < retList.size(); i++) {
			Map rowMap = (Map) retList.get(i);
			String value = String.valueOf(rowMap.get(colName)).trim();
			Integer level = (Integer)rowMap.get(TreeConstant.LEVEL_NAME);
			rowMap.put(String.valueOf(formulaInfo.getColNum()), value);
			rowMap.put(FormulaConstant.COMPARE_NAME, String.valueOf(rowMap.get(compareName)));
			
			//记录位置
			idMap.put(String.valueOf(rowMap.get(compareName)), new Integer(i));
			//记录父节点的位置
			rowMap.put(TreeConstant.PARENT_POSITION_NAME, idMap.get(rowMap.get(parentIdName)));
		}

		return retList;
	}

}
